<template>
  <div class="tem-div">
    <!--搜索-->
    <Card class="tem-card">
      <div class="search-item" :style="searchItemStyle">
        <Form ref="searchForm" label-position="right" inline :label-width="60" class="frm-search">
          <FormItem label="角色名称">
            <i-input placeholder="角色名称" v-model="searchData.name"></i-input>
          </FormItem>
        </Form>
      </div>
      <div class="search-btn">
        <hy-icon-btn @click="changeSearchDiv" :text="searchDiv?'收起更多':'展开更多'" :iconType="searchDiv?'chevron-up':'chevron-down'" iconSize="12"></hy-icon-btn>
        <Button type="primary" @click="search(1)" icon="search" :loading="searchListLoading">搜索</Button>
        <i class="search-i"></i>
        <Button class="search-btn-plus" type="ghost" v-btnAuth="{code: 'userAdd'}" icon="plus" @click="showModal('add')">新增</Button>
      </div>
    </Card>
    <!--按钮-->
    <!--<Card class="tem-card">
      <div style="text-align: left">
        <i-button v-btnAuth="{code: 'roleAdd'}" @click="showModal('add')">新增</i-button>
         <i-button v-btnAuth="{code: ''}" @click="authItem()">测试</i-button>
      </div>
    </Card>-->
    <!--表格-->
    <Card class="tem-card">
      <!--table部分-->
      <Table border :columns="columnsTitle" :loading="searchListLoading" :data="list" @on-selection-change="handleSelectionChange"></Table>
      <br>
      <!-- 分页 -->
      <Page :total="totalElement"
            :current="searchData.pageNum"
            size="small"
            show-elevator
            show-sizer
            show-total
            style="text-align: right;"
            @on-change="search"
            @on-page-size-change="pageSizeChange"
            :page-size-opts="pageSizeOpts"
      ></Page>
    </Card>
    <!--弹出框-->
    <Modal v-model="modalObj.addOrModify" :mask-closable="false">
      <p slot="header">
        <span>{{modalObj.title}}</span>
      </p>
      <div style="text-align:center">
        <Form ref="form" :model="modalFormData" :rules="ruleValidate" :label-width="80">
          <hy-form-item :form="modalFormData" :formRow="modalFormItem"></hy-form-item>
        </Form>
      </div>
      <div slot="footer">
        <i-button type="success" size="large" :loading="actionLoading" @click="addOrUp('form')">确定</i-button>
        <i-button size="large" @click="modalObj.addOrModify = false">取消</i-button>
      </div>
    </Modal>
    <!--授权树-->
    <Modal v-model="modalTree" :mask-closable="false" width="360">
      <p slot="header">
        <span>角色授权</span>
      </p>
      <div style="text-align:left;margin-left: 40px;">
        <zTree :zNodes="treeData" @result="handleResult"></zTree>
      </div>
      <div slot="footer">
        <i-button type="success" size="large" :loading="actionLoading" @click="saveAuth">确定</i-button>
        <i-button size="large" @click="modalTree = false">取消</i-button>
      </div>
    </Modal>
  </div>
</template>
<script>
  // import $ from 'jQuery';
  import fetch from './service';
  import list from '@/js/mixins/list';
  import HyFormItem from '@/components/common/formItem/formItem.vue';
  import HyDetail from '@/components/common/detail/detail.vue';
  import zTree from '@/components/zTree/zTree.vue';

  export default {
    components: {
      HyDetail,
      HyFormItem,
      zTree
    },
    mixins: [list],
    data () {
      return {
        loading: false,
        // 查询条件
        searchObj: {},
        modalObj: {
          title: '',
          addOrModify: false
        },
        modalTree: false,
        columnsTitle: [
          {
            key: 'name',
            title: '角色',
            width: 120
          },
          {
            key: 'remarks',
            title: '备注'
          },
          {
            title: '操作',
            key: 'action',
            width: 190,
            fixed: 'right',
            align: 'center',
            render: (h, params) => {
              return h('div', [
                this._hyTool.createIconBtn(h, params, this.editItem, '编辑', 'edit', 20, {color: '#2db7f5'}, 'roleEdit'),
                this._hyTool.createIconBtn(h, params, this.authItem, '授权', 'ios-people', 20, {color: '#2db7f5'}, 'roleAuth'),
                this._hyTool.createIconBtn(h, params, this.deleteItem, '删除', 'trash-a', 20, {color: 'red'}, 'roleDelete')
              ]);
            }
          }
        ],
        modalFormData: {
          name: '',
          remarks: '',
          buttonIdList: []
        },
        modalFormItem: [
          {
            key: 'name',
            title: '角色名字'
          },
          {
            key: 'remarks',
            title: '备注',
            type: 'textarea'
          }
        ],
        ruleValidate: {
          name: [
            {required: true, message: '姓名不能为空', trigger: 'blur'},
            {max: 20, message: '角色名称不能超过20个字符且不包含空格', trigger: 'blur'}
          ],
          remarks: [
            {max: 200, message: '备注不能超过200个字符且不包含空格', trigger: 'blur'}
          ]
        },
        treeData: [],
        treeObj: {}
      };
    },
    created () {
      // 初始化按钮权限列表
     this.getAuthTree();
    },
    methods: {
      _getList () {
        // 作用合并搜索条件
       fetch.getList(Object.assign(this.searchData, this.searchObj)).then(this.callback);
      },
      clearFormValid () {
        this.$refs.form.resetFields();
      },
      getById (row) {
        fetch.getOne({id: row.id}).then((result) => {
          this.modalFormData = result.data;
        });
      },
      getAuthTree () {
        fetch.treeApi().then((result) => {
          this.treeData = result.data;
        });
      },
      addOrUp (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this._hyTool.cal(true);
            try {
              if (this.modalObj.title === '新增') {
                fetch.saveApi(this.modalFormData).then((data) => {
                  this.$Notice.success({
                    title: '新增成功'
                  });
                  this.search();
                });
              } else {
                let opt = {id: this.modalFormData.id};
                fetch.updateApi(opt, this.modalFormData).then((data) => {
                  this.$Notice.success({
                    title: '修改成功'
                  });
                  this.search();
                });
              }
            } catch (e) {}
            this.modalObj.addOrModify = false;
            this._hyTool.cal(false);
          }
        });
      },
      editItem (row) {
        this.modalObj.title = '编辑';
        this.modalObj.addOrModify = true;
        this.clearFormValid();
        this.getById(row);
      },
      deleteItem (row) {
        this.$Modal.confirm({
          title: '提示',
          content: '是否删除角色：' + row.name,
          onOk: () => {
            let payload = {id: row.id};
            fetch.deleteApi(payload).then((data) => {
              this.$Notice.success({title: '删除成功'});
              this.search();
            });
          }
        });
      },
      authItem (row) {
        fetch.getOne({id: row.id}).then((result) => {
          // 取消全选
          this.treeObj.checkAllNodes(false);
          // 收缩所有节点
          this.treeObj.expandAll(false);
          let chd = {};
          for (let i = 0, len = result.data.buttonIdList.length; i < len; i++) {
              chd = this.treeObj.getNodeByParam('id', result.data.buttonIdList[i], null);
              // 判断是否存在子节点
              if ('children' in chd) {
                  // 展开节点
                  this.treeObj.expandNode(chd, true);
                  // 遍历选择树状权权限
                  this.treeObj.checkNode(chd, true, false);
              } else {
                  this.treeObj.checkNode(chd, true, false);
              }
          }
          this.modalFormData = result.data;
          console.log('this.modalFormData', this.modalFormData);
          // 延时打开模态框
          setTimeout(() => {
            this.modalTree = true;
          }, 500);
        });
      },
      saveAuth () {
        // 获取buttonList
        let checkCount = this.treeObj.getCheckedNodes(true);
        this.modalFormData.buttonIdList = [];
        checkCount.forEach(element => {
            this.modalFormData.buttonIdList.push(element.id);
        });
        try {
          let opt = {id: this.modalFormData.id};
          fetch.updateApi(opt, this.modalFormData).then((data) => {
            this.$Notice.success({
              title: '授权成功'
            });
            this.modalTree = false;
          });
        } catch (e) {}
      },
      handleResult (res) {
        // 获取子组件树对象
        console.log(res);
        this.treeObj = res;
      }
    }
  };
</script>
